package wxapp

import (
	"github.com/medivhzhan/weapp/v2"
	"h8QuestionnaireServer/components/config"
	"io/ioutil"
	"time"

	"github.com/medivhzhan/weapp/token"
	"github.com/rs/zerolog/log"
)

var accessToken string
var period = time.Second * 7100
var timer = time.NewTimer(period)

func init() {
	go refreshToken()
}

func refreshToken() {
	for {
		var err error
		var exp time.Duration
		accessToken, exp, err = token.AccessToken(config.Config.Wxapp.Appid, config.Config.Wxapp.Secret)
		if err != nil {
			log.Error().Msgf("token refresh error %v", err)
		} else {
			if exp < period && exp > time.Second*100 {
				period = exp - time.Second*100
			}
			log.Info().Msgf("token refreshed: exp in %v, accessToken %s", exp, accessToken)
		}
		timer.Reset(period)
		<-timer.C
	}
}

func GetAccessToken() string {
	return accessToken
}

// 生成无限菊花码
func CreateUnlimitedQRCode(page, scene string, width int) (content []byte, err error) {
	getter := weapp.UnlimitedQRCode{
		Scene: scene,
		Page:  page,
	}

	if width > 0 {
		getter.Width = width
	}

	resp, res, err := getter.Get(GetAccessToken())
	if err != nil {
		// 处理一般错误信息
		return nil, err
	}

	if err := res.GetResponseError(); err != nil {
		// 处理微信返回错误信息
		return nil, err
	}
	defer resp.Body.Close()

	content, err = ioutil.ReadAll(resp.Body)
	return
}
